<?php

import("data.db.DbAbstractTable");
import("data.db.DbFactory");
import("type.TimeDate");
import("data.logic.catalogue.Catalogue");
import("data.logic.catalogue.Node");

class DbCatalogue extends DbAbstractTable {
	
	public $className = "data.logic.catalogue.Catalogue";
	const CLASS_NAME =  "data.logic.catalogue.Catalogue";
	
	const TB_TABLENAME	= "pd_catalog_info";
	const TB_I			= 'cat';
	
	const TB_NAME		= 'cat_name';
	const TB_CREATED	= 'cat_created';
	
	const DATETIME_FORMAT_MYSQL = "Y/m/d H:i:s";
	
	public static function _get_TABLENAME() {return self::TB_TABLENAME;}
	public static function _get_ID() {return self::TB_I."_id";}
	public static function _get_SUFFIX() {return self::TB_I;}
	
	function forwardForeignCollection() {
		return parent::forwardForeignCollection();
	}
	function backwardForeignCollection() {
		return array("Node"=>"data.logic.catalogue.Node");
	}
	
	// properties
	public $name;
	public $created;
	
	public function __construct($noinit=false) {
		parent::__construct($noinit);
		$this->setCreated(new TimeDate());
	}
	
	function setName($name) {
		if(!(strpos($name,":")===false)) {
			throw new Exception("Catalogue name cannot contein any of following characters: \ / :");
		}
		$this->name = $name;
	}
	function getName() {return $this->name;}
	
	function setCreated($value) {$this->created = $value;}
	function getCreated() {return $this->created;}
	
	function setItems(&$items) {
		$this->backwardForeigns["Node"]->setList($items);
	}
	function getItems() {
		return $this->backwardForeigns["Node"]->getList();
	}
	
	// restore
	function fillEntity($arrResult) {
		parent::fillEntity($arrResult);
		$this->setName($arrResult[self::TB_NAME]);
		$this->setCreated(new TimeDate(self::DATETIME_FORMAT_MYSQL, $arrResult[self::TB_CREATED]));
	}
	
	//store
	function fillFields() {
		parent::fillFields();
		$this->fildsForStore[self::TB_NAME] = "'".$this->getName()."'";
		$this->fildsForStore[self::TB_CREATED] = "'".$this->created->toString(self::DATETIME_FORMAT_MYSQL)."'";
	}
	
	function getRootNode() {
		return parent::__selectByCriteria(
			DbNode::TB_NAME."='root' and ".
				DbAbstractTable::_get_FOREIGN('data.logic.catalogue.Node',
					'data.logic.catalogue.Catalogue')."='".$this->getId()."'",
			'data.logic.catalogue.Node');
	}
	
	function findNodeById($id) {
		return parent::__selectByCriteria(
			DbNode::_get_ID()."='$id' and ".
				DbAbstractTable::_get_FOREIGN('data.logic.catalogue.Node',
					'data.logic.catalogue.Catalogue')."='".$this->getId()."'",
			'data.logic.catalogue.Node');
	}
	
	function findByName($name) {
		return parent::__selectByCriteria(
			self::TB_NAME."='".$name."'",
			'data.logic.catalogue.Catalogue');
	}
	
	// same for all classes
	public static function findAll() {return parent::findAll(self::CLASS_NAME);}
    public static function findById($id) {return parent::findById($id, self::CLASS_NAME);}
}
?>